package com.markerhub.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.markerhub.common.lang.Result;
import com.markerhub.common.lang.retunData;
import com.markerhub.entity.TFacilityBase;
import com.markerhub.entity.TFacilityFunction;
import com.markerhub.mapper.TFacilityFunctionMapper;
import com.markerhub.povo.TFacilityBaseVo;
import com.markerhub.service.TFacilityBaseService;
import com.markerhub.service.TFacilityFunctionService;
import org.apache.poi.hpsf.Decimal;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘佳明
 * @since 2021-12-10
 */
@Controller
@RequestMapping("/tFacilityBase")
public class TFacilityBaseController {


    @Autowired
    TFacilityBaseService tFacilityBaseService;
    @Autowired
    TFacilityFunctionService tFacilityFunctionService;


    @Autowired
    TFacilityFunctionMapper tFacilityFunctionMapper;


    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:facility:list')")
    @ResponseBody
    public retunData list(Integer page, Integer limit, String address, String projectid, Integer type, Integer model, String math) {

        System.out.println(page);
        System.out.println(limit);
        System.out.println(projectid);
        System.out.println(type);
        System.out.println(model);
        System.out.println(math);
        if (limit==0&&limit==0){
            List<TFacilityBase> list = tFacilityBaseService.list();
            retunData retunData1 = new retunData();
            retunData1.setData(list);
            return retunData1;
        }
        Integer pages=(page-1)*limit;

        List<TFacilityBaseVo> TFacilityBaseVoList= tFacilityBaseService.getFacilityList(pages,limit,math,model,type,address,projectid);
        List<TFacilityBaseVo> count= tFacilityBaseService.getFacilityList(0,0,math,model,type,address,projectid);
       // System.out.println("List<TFacilityBaseVo> count "+count);
        retunData retunData = new retunData();
        retunData.setData(TFacilityBaseVoList);
        retunData.setCount(count.size());


        return retunData;
    }



    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:facility:add')")
    @ResponseBody
    @Transactional
    public  Result add(@Validated  @RequestBody TFacilityBase tFacilityBase){
        //System.out.println("================="+tFacilityBase);
        List<TFacilityBase> number = tFacilityBaseService.list(new QueryWrapper<TFacilityBase>().eq("number", tFacilityBase.getNumber()));
        if (number.size()>0){
            return Result.fail("该设备编号已存在！！");
        }
        boolean save = tFacilityBaseService.save(tFacilityBase);
        TFacilityFunction tFacilityFunction1 = new TFacilityFunction();
        tFacilityFunction1.setBaseid(tFacilityBase.getId());
        tFacilityFunction1.setMoney(new BigDecimal(0.10));
        tFacilityFunction1.setFunctionType("洁桶");
        tFacilityFunction1.setFunctionStatus(1);
        tFacilityFunction1.setFunctionTime(3);
        tFacilityFunction1.setDescribes("清洁洗衣机滚筒内壁！！！大约5分钟");
//        TFacilityFunction tFacilityFunction2 = new TFacilityFunction();
//        TFacilityFunction tFacilityFunction3 = new TFacilityFunction();
//        TFacilityFunction tFacilityFunction4 = new TFacilityFunction();
        boolean save1 = tFacilityFunctionService.save(tFacilityFunction1);
        if (save1){
            TFacilityFunction tFacilityFunction2 = new TFacilityFunction();
            tFacilityFunction2.setMoney(new BigDecimal(1.0));
            tFacilityFunction2.setBaseid(tFacilityBase.getId());
            tFacilityFunction2.setFunctionType("脱水");
            tFacilityFunction2.setFunctionTime(10);
            tFacilityFunction2.setDescribes("适用3/4 洗净待脱水的衣物！！！大约20分钟");
            tFacilityFunction2.setFunctionStatus(1);
            boolean save2 = tFacilityFunctionService.save(tFacilityFunction2);
            if (save2){
                TFacilityFunction tFacilityFunction3 = new TFacilityFunction();
                tFacilityFunction3.setMoney(new BigDecimal(2.0));
                tFacilityFunction3.setBaseid(tFacilityBase.getId());
                tFacilityFunction3.setFunctionType("快速洗");
                tFacilityFunction3.setFunctionTime(25);
                tFacilityFunction3.setDescribes("适用3/4 轻度脏污的衣物！！！大约25分钟");
                tFacilityFunction3.setFunctionStatus(1);
                boolean save3 = tFacilityFunctionService.save(tFacilityFunction3);
                if (save3){
                    TFacilityFunction tFacilityFunction4 = new TFacilityFunction();
                    tFacilityFunction4.setBaseid(tFacilityBase.getId());
                    tFacilityFunction4.setMoney(new BigDecimal(3.0));
                    tFacilityFunction4.setFunctionType("标准洗");
                    tFacilityFunction4.setFunctionTime(35);
                    tFacilityFunction4.setDescribes("适用3/4 脏污的衣物！！！大约35分钟");
                    tFacilityFunction4.setFunctionStatus(1);

                    boolean save4 = tFacilityFunctionService.save(tFacilityFunction4);
                    if (save4) {
                        TFacilityFunction tFacilityFunction5 = new TFacilityFunction();
                        tFacilityFunction5.setBaseid(tFacilityBase.getId());
                        tFacilityFunction5.setMoney(new BigDecimal(4.0));
                        tFacilityFunction5.setFunctionType("加强洗");
                        tFacilityFunction5.setFunctionTime(45);
                        tFacilityFunction5.setDescribes("适用3/4 重度脏污的衣物！！！大约45分钟");
                        tFacilityFunction5.setFunctionStatus(1);

                        boolean save5 = tFacilityFunctionService.save(tFacilityFunction5);
                        return Result.succ(tFacilityBase);
                    }
                }
            }

        }
        return Result.fail("新增设备信息失败！！！");
    }
    @RequestMapping("/updata")
    @PreAuthorize("hasAuthority('sys:facility:updata')")
    @ResponseBody
    public  Result updata(String id,Integer types,Integer models,String number,String projectid,Integer manufactors, Integer status){
        List<TFacilityBase> numbera = tFacilityBaseService.list(new QueryWrapper<TFacilityBase>().eq("number", number));
        if (numbera.size()>0){
            return Result.fail("该设备编号已存在！！");
        }
        TFacilityBase tFacilityBase = new TFacilityBase();
        tFacilityBase.setId(id);
        tFacilityBase.setNumber(number);
        tFacilityBase.setManufactor(manufactors);
        tFacilityBase.setModel(models);
        tFacilityBase.setType(types);
        tFacilityBase.setProjectid(projectid);
        tFacilityBase.setStatus(status);
        System.out.println("================="+tFacilityBase);
        boolean save = tFacilityBaseService.updateById(tFacilityBase);
        return Result.succ(tFacilityBase);
    }
    @RequestMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:facility:delete')")
    @ResponseBody
    @Transactional
    public  Result delete(@PathVariable("id") String id){
        System.out.println("sys:facility:delete === >>"+id);
        boolean delete = tFacilityBaseService.removeById(id);
        boolean id1 = tFacilityFunctionService.remove(new QueryWrapper<TFacilityFunction>().eq("baseid", id));
        return Result.succ(null);
    }
    @RequestMapping("/claim")
    @PreAuthorize("hasAuthority('sys:facility:claim')")
    @ResponseBody
    public  Result claim(@Validated @RequestBody TFacilityBase tFacilityBase){

        System.out.println(tFacilityBase.getAddress());
        System.out.println(tFacilityBase.getNumber());
        System.out.println(tFacilityBase.getProjectid());
        List<TFacilityBase> list = tFacilityBaseService.list(new QueryWrapper<TFacilityBase>().eq("number", tFacilityBase.getNumber()).eq("projectid", tFacilityBase.getProjectid()));
        if (list.size()>0){
            TFacilityBase tFacilityBase1 = list.get(0);
//            if (tFacilityBase1.getStatus()!=1){
//                tFacilityBase1.setStatus(1);
//            }
            tFacilityBase1.setStatus(1);

            tFacilityBase1.setAddress(tFacilityBase.getAddress());
            boolean b = tFacilityBaseService.updateById(tFacilityBase1);
            return  Result.succ(null);
        }else {
            return  Result.fail("没有找到改项目中符合编号的设备信息，无法认领！！！");
        }


    }



//    @GetMapping("/export")
//    @PreAuthorize("hasAuthority('sys:facility:export')")
//    public void download(HttpServletResponse response) throws IOException {
//        List<TFacilityBase> list = tFacilityBaseService.list();
//       // List<TradingRecord> list = new ArrayList<TradingRecord>();
//        String name = "VGM对账清单.xlsx";
//        // 导出时候会出现中文无法识别问题，需要转码
//        String fileName = new String(name.getBytes("gb2312"),"ISO8859-1");
//        response.setContentType("application/vnd.ms-excel;chartset=utf-8");
//        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
//        //调用工具类
//        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();
//        WriteSheet sheet = EasyExcel.writerSheet(0,"sheet").head(TFacilityBase.class).build();
//        writer.write(list,sheet);
//        writer.finish(); // 使用完毕之后要关闭
//
//    }
@PostMapping("/importExecl")
@PreAuthorize("hasAuthority('sys:facility:importExecl')")
@ResponseBody
public Map<String,Object> noEntity(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
    Map<String,Object> result = new HashMap<>();
    List<Object> list = EasyExcel.read(excelFile.getInputStream()).sheet(0).doReadSync();
    result.put("list", list);
    System.out.println(list);
    return result;
}

    @PostMapping("/download")
    @PreAuthorize("hasAuthority('sys:facility:export')")
    public void downloadexecl(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+fileName+".xlsx");
        EasyExcel.write(response.getOutputStream()).sheet("第一个sheet").doWrite(data());
        //return Result.succ(null);
    }

    protected List<?> data(){
        List<List<String>> rowList = new ArrayList<>();
        List<String> cell = new ArrayList<>();
        cell.add("good1");
        cell.add("good2");
        cell.add("good3");
        rowList.add(cell);
        return rowList;
    }


//    public void writeTradingRecord(HttpServletResponse   response,AppreciationServiceRequest appreciationServiceRequest) throws IOException {
//        List<TradingRecord> list = new ArrayList<TradingRecord>();
//        String name = "VGM对账清单.xlsx";
//        // 导出时候会出现中文无法识别问题，需要转码
//        String fileName = new String(name.getBytes("gb2312"),"ISO8859-1");
//        response.setContentType("application/vnd.ms-excel;chartset=utf-8");
//        response.setHeader("Content-Disposition","attachment;filename=" + fileName);
//        //调用工具类
//        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();
//        WriteSheet sheet = EasyExcel.writerSheet(0,"sheet").head(TradingRecord.class).build();
//        writer.write(list,sheet);
//        writer.finish(); // 使用完毕之后要关闭
//    }





}

